<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{ templateName }} - 字段管理</span>
        <div style="float: right;">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-check"
            @click="handleSave"
            :loading="saveLoading">
            保存模版
          </el-button>
          <el-button
            size="small"
            icon="el-icon-back"
            @click="handleBack">
            返回
          </el-button>
        </div>
      </div>

      <el-row :gutter="20" style="margin-bottom: 10px;">
        <el-col :span="24">
          <el-alert
            title="字段管理说明"
            type="info"
            :closable="false"
            show-icon>
            <div><b>使用方法：</b>在Excel的<b>第一行</b>输入字段名称，尽量每一个字段不要重名，可以自由调整列宽度</div>
            <ul style="margin: 10px 0; padding-left: 20px;">
              <li><b>字符串字段：</b>"姓名"</li>
              <li><b>下拉列表字段：</b>首先要选中整列-》菜单开始-》单元格编辑器-》单元格类型-》组合框，设置即可，例如："招聘状态：待招聘、招聘中、招聘完成"</li>
              <li><b>排序规则：</b>按照Excel中的列顺序（从左到右）</li>
            </ul>
            <div style="color: #E6A23C;">
              <i class="el-icon-warning"></i>
              <b>注意：</b>删除字段前会检查是否有数据，有数据的字段不能删除！如果需要添加特殊规则，需要联系技术人员操作。
            </div>
          </el-alert>
        </el-col>
      </el-row>

      <!-- SpreadJS表格 -->
      <div style="height: 600px; border: 1px solid #ddd;">
        <spread-js
          ref="spreadjs"
          :columns="columns"
          :data="fieldData"
          :readonly="false"
          :use-designer="true"
          @ready="onSpreadReady"
          :container-id="spreadjsId"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import SpreadJS from '@/components/SpreadJS/index.vue'
import { getTemplate, getFieldList, saveFieldList } from '@/api/talent/template'

export default {
  name: 'TemplateFields',
  components: {
    'spread-js': SpreadJS
  },
  watch: {
    '$route.query.id'(newId) {
      this.onRouteIdChange(newId)
    }
  },
  data() {
    return {
      templateId: null,
      templateName: '',
      tableName: '',
      saveLoading: false,
      // SpreadJS列配置 - 空数组，让用户在Designer模式下自由设计
      columns: [],
      // 字段数据
      fieldData: [],
      // SpreadJS容器ID（唯一）
      spreadjsId: 'template-fields-spreadjs-' + Date.now(),
      // 待填充的字段标签（从后端加载）
      pendingFieldLabels: [],
      // 待应用的列宽（与字段标签一一对应）
      pendingColumnWidths: [],
      // 待恢复的单元格类型配置（与字段标签一一对应）
      pendingCellTypeConfigs: [],
      // 原始字段数据（用于跟踪字段ID，支持重命名）
      originalFields: [],

    }
  },
  created() {
    // 从路由参数获取模板ID
    this.templateId = this.$route.query.id
    if (!this.templateId) {
      this.$modal.msgError('缺少模板ID参数')
      this.handleBack()
      return
    }
    this.loadTemplateInfo()
    this.loadFieldList()
  },
  methods: {
    // 路由参数变化处理
    onRouteIdChange(newId) {
      if (!newId || newId === this.templateId) return
      this.templateId = newId
      this.templateName = ''
      this.tableName = ''
      this.pendingFieldLabels = []
      this.pendingColumnWidths = []
      this.pendingCellTypeConfigs = []
      this.originalFields = []

      // 清空当前表头行，避免残留旧数据
      const spreadjs = this.$refs.spreadjs
      if (spreadjs && spreadjs.sheet) {
        const sheet = spreadjs.sheet
        try {
          sheet.suspendPaint()
          const colCount = sheet.getColumnCount()
          for (let c = 0; c < colCount; c++) {
            sheet.setValue(0, c, '')
          }
        } finally {
          sheet.resumePaint()
        }
      }

      // 重新加载新模板信息与字段
      this.loadTemplateInfo()
      this.loadFieldList()
    },
    // 加载模板信息
    loadTemplateInfo() {
      getTemplate(this.templateId).then(response => {
        this.templateName = response.data.postName + '人才库'
        this.tableName = response.data.tableName
      })
    },

    // 加载字段列表
    loadFieldList() {
      getFieldList(this.templateId).then(response => {
        const rows = response.rows || []
        if (!rows.length) return

        // 保存完整的原始字段数据（包含ID）
        this.originalFields = rows.map(r => ({ ...r }))

        this.pendingFieldLabels = rows.map(r => r.fieldLabel)
        this.pendingColumnWidths = rows.map(r => (r.columnWidth && Number(r.columnWidth)) || 120)

        // 保存字段的cellTypeConfig配置，用于恢复
        this.pendingCellTypeConfigs = rows.map(r => {
          if (r.cellTypeConfig) {
            try {
              const config = JSON.parse(r.cellTypeConfig)
              return config
            } catch (e) {
              console.error(`解析字段 "${r.fieldLabel}" 的cellTypeConfig失败:`, e)
              return null
            }
          }
          return null
        })

        // 如果Spread已就绪，立即填充；否则在ready事件中填充
        this.$nextTick(() => {
          this.fillHeadersIfReady()
        })
      })
    },

    // SpreadJS 就绪
    onSpreadReady() {
      this.fillHeadersIfReady()
    },

    // 如果组件就绪则填充表头
    fillHeadersIfReady() {
      const spreadjs = this.$refs.spreadjs
      if (!spreadjs || !spreadjs.sheet || !this.pendingFieldLabels.length) return
      const sheet = spreadjs.sheet
      sheet.suspendPaint()
      // 先清空表头行，避免残留旧模板的标题
      const colCount = sheet.getColumnCount()
      for (let c = 0; c < colCount; c++) {
        sheet.setValue(0, c, '')
      }
      this.pendingFieldLabels.forEach((label, index) => {
        // 设置表头
        sheet.setValue(0, index, label)

        // 设置列宽
        const width = this.pendingColumnWidths && this.pendingColumnWidths[index] ? this.pendingColumnWidths[index] : 120
        sheet.setColumnWidth(index, width)

        // 恢复单元格类型配置
        const cellTypeConfig = this.pendingCellTypeConfigs && this.pendingCellTypeConfigs[index]
        if (cellTypeConfig) {
          console.log(`🔧 [DEBUG] 恢复列 ${index} "${label}" 的单元格类型:`, cellTypeConfig)
          this.restoreCellType(sheet, index, cellTypeConfig)
        }
      })
      sheet.resumePaint()
      // 强制刷新一次，避免需要点击后才渲染正确
      try {
        if (spreadjs.spread && spreadjs.spread.refresh) spreadjs.spread.refresh()
        if (sheet && sheet.repaint) sheet.repaint()
      } catch (e) {}

      // 通过切换一次激活单元格来强制触发渲染（模拟一次点击）
      try {
        const oldRow = sheet.getActiveRowIndex()
        const oldCol = sheet.getActiveColumnIndex()
        // 临时切换到数据区第一格再切回去
        sheet.setActiveCell(1, 0)
        if (oldRow != null && oldRow >= 0 && oldCol != null && oldCol >= 0) {
          sheet.setActiveCell(oldRow, oldCol)
        } else {
          sheet.setActiveCell(0, 0)
        }
      } catch (e) {}

      // 再次推迟到下一帧刷新，确保视觉稳定
      this.$nextTick(() => {
        setTimeout(() => {
          try {
            if (spreadjs.spread && spreadjs.spread.refresh) spreadjs.spread.refresh()
            if (sheet && sheet.repaint) sheet.repaint()
          } catch (e) {}
        }, 0)
      })
    },

    // 保存字段
    handleSave() {
      const spreadjs = this.$refs.spreadjs
      if (!spreadjs || !spreadjs.spread || !spreadjs.sheet) {
        this.$modal.msgError('SpreadJS未正确初始化')
        return
      }

      const sheet = spreadjs.sheet
      const colCount = sheet.getColumnCount()

      // 读取当前SpreadJS中的字段名称和列宽
      const currentFieldLabels = []
      const currentColumnWidths = []
      for (let col = 0; col < colCount; col++) {
        const value = sheet.getValue(0, col)
        if (value && value.toString().trim() !== '') {
          currentFieldLabels.push(value.toString().trim())
          const width = sheet.getColumnWidth(col)
          currentColumnWidths.push(Math.round(width))
        }
      }

      if (currentFieldLabels.length === 0) {
        this.$modal.msgWarning('请至少在第一行添加一个字段名称')
        return
      }

      // 检查字段名称重复
      const uniqueLabels = new Set(currentFieldLabels)
      if (uniqueLabels.size !== currentFieldLabels.length) {
        this.$modal.msgError('字段名称不能重复')
        return
      }

      // 构建字段数据，智能匹配原始字段ID
      const GC = window.GC
      const fields = currentFieldLabels.map((currentLabel, currentIndex) => {
        // 尝试匹配原始字段：
        // 1. 首先按位置匹配（假设字段顺序没有大幅改变）
        // 2. 如果位置匹配失败，按标签匹配
        let originalField = null

        // 按位置匹配
        if (this.originalFields[currentIndex] &&
            this.originalFields[currentIndex].fieldLabel === currentLabel) {
          originalField = this.originalFields[currentIndex]
        }
        // 按标签匹配（处理字段顺序变更的情况）
        else {
          originalField = this.originalFields.find(f => f.fieldLabel === currentLabel)
        }

        // 如果没找到完全匹配，可能是字段重命名，尝试按位置匹配
        if (!originalField && this.originalFields[currentIndex]) {
          originalField = this.originalFields[currentIndex]
        }

        // 读取单元格类型配置
        let cellTypeConfig = null
        let cellType = null
        for (let checkRow = 1; checkRow <= 3; checkRow++) {
          const tempCellType = sheet.getCellType(checkRow, currentIndex, GC.Spread.Sheets.SheetArea.viewport)
          if (tempCellType && (tempCellType.items || tempCellType.textTrue || tempCellType.textFalse)) {
            cellType = tempCellType
            break
          }
        }

        if (!cellType) {
          cellType = sheet.getCellType(1, currentIndex, GC.Spread.Sheets.SheetArea.viewport)
        }

        // 处理ComboBox
        if (cellType && typeof cellType.items === 'function') {
          try {
            const itemsArray = cellType.items() || []
            const items = itemsArray.map(item => {
              if (typeof item === 'object' && item.text) {
                return item.text
              } else if (typeof item === 'string') {
                return item
              } else {
                return String(item)
              }
            })

            let editable = true
            if (typeof cellType.editable === 'function') {
              try { editable = cellType.editable() } catch (e) {}
            } else if (typeof cellType.editable === 'boolean') {
              editable = cellType.editable
            }

            if (items && items.length > 0) {
              cellTypeConfig = JSON.stringify({
                type: 'combobox',
                items: items,
                editable: editable
              })
            }
          } catch (e) {
            console.error('处理ComboBox失败:', e)
          }
        }
        // 处理CheckBox
        else if (cellType && (cellType.textTrue || cellType.textFalse || cellType.typeName === 'checkbox')) {
          let textTrue = '是'
          let textFalse = '否'

          if (typeof cellType.textTrue === 'function') {
            try { textTrue = cellType.textTrue() } catch (e) {}
          } else if (cellType.textTrue) {
            textTrue = cellType.textTrue
          }

          if (typeof cellType.textFalse === 'function') {
            try { textFalse = cellType.textFalse() } catch (e) {}
          } else if (cellType.textFalse) {
            textFalse = cellType.textFalse
          }

          cellTypeConfig = JSON.stringify({
            type: 'checkbox',
            textTrue: textTrue,
            textFalse: textFalse
          })
        }

        // 构建字段对象
        const fieldObj = {
          templateId: this.templateId,
          fieldLabel: currentLabel,
          isRequired: originalField ? originalField.isRequired : '0',
          sortOrder: currentIndex + 1,
          columnWidth: currentColumnWidths[currentIndex] || 120,
          cellTypeConfig: cellTypeConfig,
          remark: originalField ? originalField.remark : '',
          // 关键：保留原始字段信息以支持字段变更检测
          originalField: originalField
        }

        return fieldObj
      })

      this.saveLoading = true
      saveFieldList(this.templateId, fields).then(() => {
        this.$modal.msgSuccess('保存成功')
        this.loadFieldList()
      }).catch(error => {
        this.$modal.msgError('保存失败: ' + (error.msg || error.message || '未知错误'))
      }).finally(() => {
        this.saveLoading = false
      })
    },

    // 恢复单元格类型
    restoreCellType(sheet, colIndex, cellTypeConfig) {
      const GC = window.GC
      if (!GC || !GC.Spread || !GC.Spread.Sheets) {
        console.error('🔧 [DEBUG] SpreadJS未正确加载，无法恢复单元格类型')
        return
      }

      try {
        if (cellTypeConfig.type === 'combobox' && cellTypeConfig.items) {
          console.log(`🔧 [DEBUG] 恢复ComboBox到列 ${colIndex}，选项:`, cellTypeConfig.items)

          // 创建ComboBox单元格类型
          const comboBox = new GC.Spread.Sheets.CellTypes.ComboBox()
          comboBox.items(cellTypeConfig.items)
          comboBox.editable(cellTypeConfig.editable !== false) // 默认可编辑

          // 为整列设置ComboBox（从第2行开始，不包含表头）
          for (let row = 1; row < 1000; row++) {
            sheet.setCellType(row, colIndex, comboBox, GC.Spread.Sheets.SheetArea.viewport)
          }

          console.log(`✅ [DEBUG] 成功恢复列 ${colIndex} 的ComboBox`)
        }
        else if (cellTypeConfig.type === 'checkbox') {
          console.log(`🔧 [DEBUG] 恢复CheckBox到列 ${colIndex}`)

          // 创建CheckBox单元格类型
          const checkBox = new GC.Spread.Sheets.CellTypes.CheckBox()
          if (cellTypeConfig.textTrue) checkBox.textTrue(cellTypeConfig.textTrue)
          if (cellTypeConfig.textFalse) checkBox.textFalse(cellTypeConfig.textFalse)

          // 为整列设置CheckBox（从第2行开始，不包含表头）
          for (let row = 1; row < 1000; row++) {
            sheet.setCellType(row, colIndex, checkBox, GC.Spread.Sheets.SheetArea.viewport)
          }

          console.log(`✅ [DEBUG] 成功恢复列 ${colIndex} 的CheckBox`)
        }
        else {
          console.log(`⚠️ [DEBUG] 未知的单元格类型: ${cellTypeConfig.type}`)
        }
      } catch (e) {
        console.error(`❌ [DEBUG] 恢复列 ${colIndex} 的单元格类型失败:`, e)
      }
    },

    // 返回
    handleBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

::v-deep .el-alert ul {
  list-style-type: disc;
}
</style>

